#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <sys/eventfd.h>
#include <functional>
#include <stdlib.h>
#include <poll.h>
#include <iostream>
#include <thread>


int main(int argc, char** argv)
{
    int udp_socket_ = socket(PF_INET, SOCK_DGRAM, 0);
    if (udp_socket_ == -1) {
        perror("socket error");
        return -1;
    }
    int socketoptvalue = 1;
    setsockopt(udp_socket_, SOL_SOCKET, SO_REUSEADDR, (const char*)&socketoptvalue, sizeof(int));

    sockaddr_in myAddress;                     // my address information
    // memset(&myAddress, 0, sizeof(myAddress));  // initialize to zeros
    myAddress.sin_family = AF_INET;            // host byte order
    myAddress.sin_port = htons(8899);          // port in network byte order
    myAddress.sin_addr.s_addr = INADDR_ANY;    // automatically fill in my IP

    sockaddr_in senderAddress;
    socklen_t senderAddressLen = sizeof(senderAddress);
    if (bind(udp_socket_, reinterpret_cast<sockaddr *>(&myAddress),
            sizeof(sockaddr)) == -1) {
        perror("bind");  
        return -1;
    }

    if (fcntl(udp_socket_, F_SETFL, O_NONBLOCK | FASYNC) < 0) {
        perror("non-block");
        return -1;
    }

    std::thread thread1 = std::thread([&](){
        static uint8_t cnt = 0;
        while (true)
        {
            /* code */
            char key = std::getchar();

            int v = sendto(udp_socket_, &cnt, (size_t)1, 0,(sockaddr *)&senderAddress, senderAddressLen);
            printf("send: %d  len: %d\n",cnt, v);
            cnt++;
        }
        

    });

    while (true)
    {
        /* code */
        struct pollfd fds;
        fds.fd = udp_socket_;
        fds.events = POLLIN;
        static const int POLL_TIMEOUT = 1000;  // one second (in msec)

        
        int retval = poll(&fds, 1, POLL_TIMEOUT);
        if(retval < 0){
            std::cout<<"poll err"<<std::endl;
            break;
        }
        // sockaddr_in senderAddress;
        // socklen_t senderAddressLen = sizeof(senderAddress);
        ssize_t nbytes = -1;

        uint8_t buf[1024];
        
        if (fds.revents & POLLIN) {
            nbytes = recvfrom(fds.fd, buf, 1024, 0,
                            reinterpret_cast<sockaddr *>(&senderAddress),
                            &senderAddressLen);
            printf("nbytes: %ld\n",nbytes);
            
        }
    }
    return 0;
}